<template>
  <div>
         <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <h2>角色列表</h2>
         <!-- 卡片视图区域 -->
         <el-card>
             <!-- 添加角色按钮 -->
             <el-row><el-col><el-button type="primary" @click="showAddRoles()">添加角色</el-button></el-col></el-row>
             <el-row>
                 <!-- 角色列表 -->
                   <el-table
                    :data="roleList"
                    style="width: 100%"
                    border stripe>
                      <el-table-column
                        type ="expand">
                        <!-- 展开区域 -->
                        <template slot-scope="scope">
                            <el-row :class="index==0?'bdtop bdbottom':'bdbottom' " v-for="(item1,index) in scope.row.children" :key="item1.id"  type="flex" align="middle">
                                 <!-- 一级权限 -->
                                 <el-col :span="3">
                                   <el-tag closable @close="removeRightById(scope.row.id,item1.id)" >{{item1.authName}}</el-tag>
                                   <i class="el-icon-caret-right"></i>
                                 </el-col>
                                 <!-- 二级权限 -->
                                 <el-col :span="21" class="bdleft">
                                    <el-row v-for="(item2,index) in item1.children" :key="item2.id" :class="index==0?'':'bdtop'" type="flex" align="middle"> 
                                         <el-col :span="5"><el-tag type="success" closable @close="removeRightById(scope.row.id,item2.id)" >{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                                        
                                                <el-col :span="19" >
                                                    <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row.id,item3.id)" >{{item3.authName}}</el-tag>
                                                </el-col>
                                    </el-row>
                                 </el-col>
                              
                         
                              
                              
                            </el-row>
                           
                          
                        </template>
                      </el-table-column>
                      <el-table-column
                        type ="index"
                        label="#">
                      </el-table-column>
                      <el-table-column
                        prop="roleName"
                        label="角色名称"
                      >
                      </el-table-column>
                       <el-table-column
                        prop="roleDesc"
                        label="角色描述"
                      >
                      </el-table-column>
                       <el-table-column
                        label="操作"  width="320px" >
                        <template slot-scope="scope">
                      <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoleDialog(scope.row.id)">编辑</el-button>
                      <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row.id)" >删除</el-button>
                      <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="rightsDistributing(scope.row)">分配权限</el-button>
                        </template>
                      </el-table-column>


                </el-table>
             </el-row>
         </el-card>
         <el-dialog
          title="提示"
          :visible.sync="isShowRightsDialog"
          width="50%"
          :before-close="handleClose">
          <!-- 树形控件 -->
           <el-tree :data="rightList" 
           :props="treeProps" 
           show-checkbox node-key="id"
           default-expand-all
           :default-checked-keys="defaultCheckKeys" ref="treeRef">

           </el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="distributingRights">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 添加角色对话框 -->
        <el-dialog
          title="添加角色"
          :visible.sync="isShowAddRolesDialog"
          width="50%"    >
          <el-form :rules="addRoleRules" :model="addRoleForm" label-width="80px" ref="addRoleRef" > 
              <el-form-item label="角色名称" prop="roleName">
                 <el-input  v-model="addRoleForm.roleName"></el-input>
              </el-form-item>

               <el-form-item label="角色描述" prop="roleDesc">
                 <el-input v-model="addRoleForm.roleDesc"></el-input>
              </el-form-item>
              
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="isShowAddRolesDialog = false">取 消</el-button>
            <el-button type="primary" @click="addRole">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑角色对话框 -->
         <el-dialog
          title="编辑角色信息"
          :visible.sync="isShowEditDialog"
          width="50%"    >
          <el-form :rules="addRoleRules" :model="editRoleForm" label-width="80px" ref="editRoleRef" > 
              <el-form-item label="角色名称" prop="roleName">
                 <el-input  v-model="editRoleForm.roleName"></el-input>
              </el-form-item>

               <el-form-item label="角色描述">
                 <el-input v-model="editRoleForm.roleDesc"></el-input>
              </el-form-item>
              
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="isShowEditDialog = false">取 消</el-button>
            <el-button type="primary" @click="editRole">确 定</el-button>
          </span>
        </el-dialog>
  </div>
</template>

<script>
export default {
     created() {
         this.getRoleList();
     },
     data() {
         return {
             roleList:[],
             rightList:[],
             isShowRightsDialog:false,
             //树形控件绑定对象
             treeProps:{
               label:'authName',
               children:'children'
             },
             defaultCheckKeys:[],
             roleId:'',
             //控制添加角色对话框显示  
             isShowAddRolesDialog:false,
             //控制编辑角色对话框显示  
             isShowEditDialog:false,
             //添加角色表单的数据
             addRoleForm:{
               roleName:'',
               roleDesc:''
             },
             //编辑角色表单的数据
             editRoleForm:{
               roleName:'',
               roleDesc:''
             },  
             addRoleRules:{
                  roleName:[{required:true,message:'请输入角色名称',trigger:'blur'}]
             }
         }
     },
     methods: {
         //获取角色列表
         async getRoleList(){
            const {data:res} = await this.$http.get('roles');
            if(res.meta.status !== 200 ) return this.$message.error('获取角色列表失败');
            this.$message.success('获取角色列表成功');
            this.roleList = res.data;
            console.log(this.roleList);

         },
         //根据Id删除权限
         removeRightById(roleId,rightId){
            this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
                type: 'warning'
            }).then(async() => {
            const {data:res} = await this.$http.delete(`roles/${roleId}/rights/${rightId}`);
            if(res.meta.status !== 200 ) return this.$message.error('删除权限失败');
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
            this.getRoleList();
            }).catch(() => {
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
      },
        //分配权限对话框构建
        async rightsDistributing(role){
           this.isShowRightsDialog=true;
           this.roleId = role.id;
           const {data:res} = await this.$http.get(`rights/${'tree'}`);
           if(res.meta.status != 200 ) return this.$message.error('获取失败');
          this.rightList = res.data;
        
          // 获取节点的三级权限
          this.getLeafKeys(role,this.defaultCheckKeys);
       
        },
        //关闭分配权限对话框时的回调
        handleClose(){
          this.defaultCheckKeys =[];
          this.isShowRightsDialog = false;
        },
        //通过递归获取所有角色下三级权限的id
        getLeafKeys(node,arr){
           if(!node.children){
              return arr.push(node.id);
           }
           node.children.forEach(item =>{
               this.getLeafKeys(item,arr);
           })
          
        },
        //点击为角色分配权限
        async distributingRights(){
           const keys = [
             ...this.$refs.treeRef.getCheckedKeys(),
             ...this.$refs.treeRef.getHalfCheckedKeys()]
          
           const idStr = keys.join(',');
           const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
           if(res.meta.status !== 200 ) return this.$message.error('分配失败');
           this.$message.success('分配成功');
           this.getRoleList();
           
           this.isShowRightsDialog = false;
        },
        // 显示添加用户对话框
        showAddRoles(){
            this.isShowAddRolesDialog = true;
        },
        //点击添加角色
        async addRole(){
            this.$refs.addRoleRef.validate(async valid=>{
               if(!valid) return this.isShowAddRolesDialog = false;
               const {data:res} = await this.$http.post('roles',this.addRoleForm);
               if(res.meta.status !== 201 ) return this.$message.error('添加失败');
               this.getRoleList();
               this.isShowAddRolesDialog = false;

            })
        },
        //删除角色
        removeRole(roleId){
            this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then( async() => {
              const {data:res} = await this.$http.delete(`roles/${roleId}`);
              if(res.meta.status !== 200 ) return this.$message.error('删除失败');
              this.getRoleList();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });          
            });
          },
          //编辑角色对话框显示
          async editRoleDialog(roleId){
              this.roleId = roleId;
              const {data:res} = await this.$http.get(`roles/${roleId}`);
              if(res.meta.status !== 200 ) return;
              this.editRoleForm = res.data;
              //显示对话框
              this.isShowEditDialog = true;

          },

          //编辑角色
          editRole(){
             this.$refs.editRoleRef.validate(async valid=>{
                if(!valid) return  this.isShowEditDialog = false;
                const {data:res} = await this.$http.put(`roles/${this.roleId}`,this.editRoleForm)
                if(res.meta.status != 200 ) return this.$message.error('修改角色信息失败');
                this.getRoleList();
                this.isShowEditDialog = false;
             })
             
          }

        }


    
     
}
</script>
  
<style lang="less" scoped>
      .el-tag{
          margin: 7px;
      }
      .bdtop{
          border-top: 1px solid #eee;
      }
      .bdbottom{
          border-bottom: 1px solid #eee;
      }
      .bdleft{
          border-left: 1px solid #eee;
      }
</style>